import { Button } from "antd";
import Loading from "../Loading";
import classNames from "classnames";
import Breadcrumb from "../Breadcrumb";
import type { ButtonProps } from "antd";
import type { FC, ReactElement } from "react";
import { LeftOutlined } from "@ant-design/icons";
import styles from "./styles.module.less";

interface IRight {
  showButton?: boolean;
  element?: ReactElement | null;
  buttonText?: string;
  onClick?: () => void;
  buttonProps?: ButtonProps;
}

interface IHeader {
  showBack?: boolean;
  title?: ReactElement | string | null;
  extend?: ReactElement | null;
}

interface IProps {
  children?: any;
  loading?: boolean;
  right?: IRight | false;
  breadcrumbTitle?: string;
  header?: IHeader | false;
  flexContent?: boolean;
}

const PageWrapper: FC<IProps> = (props) => {
  const {
    right,
    loading,
    children,
    flexContent,
    header = false,
  } = props;

  const renderBack = () => {
    return (
      <Button
        type="text"
        icon={<LeftOutlined />}
        className={styles.back_button}
        onClick={() => history.back()}
      />
    );
  }

  const renderRight = () => {
    if (right === false) {
      return null;
    }
    if (right?.element) {
      return right?.element;
    }
    return (
      <Button
        type="primary"
        onClick={right?.onClick}
        {...right?.buttonProps}
      >
        {right?.buttonText}
      </Button>
    );
  };

  const renderHeader = () => {
    if (header === false) return null;

    const titleNode = (() => {
      const title = header?.title;
      if (!title) return null;
      if (typeof title !== "string") {
        return title;
      };
      return (
        <div className={styles.header_title}>
          <span className={styles.title_text}>
            {title}
          </span>
          {header?.extend}
        </div>
      );
    })();

    return (
      <div className={styles.page_header}>
        <div className={styles.page_header_left}>
          {header?.showBack && renderBack()}
          {titleNode}
        </div>
        <div className={styles.page_header_right}>{renderRight()}</div>
      </div>
    );
  }

  return (
    <div className={styles.page_wrapper}>
      <Breadcrumb lastTitle={props.breadcrumbTitle} />
      <div className={styles.page_content}>
        {renderHeader()}
        <div className={classNames(
          styles.content,
          loading && styles.has_loading,
          flexContent && styles.flex_content
        )}
        >
          {!loading ? children : <Loading />}
        </div>
      </div>
    </div>
  );
};

export default PageWrapper;
